import { Button, Input, Popconfirm } from 'antd'
import services from "@/services"
import { type QywxAPIConfig } from '@/services/features/web-config'

export function QywxConnect() {
  const [configs, setConfigs] = useState<QywxAPIConfig[]>([])
  useEffect(() => {
    void services.features.webConfig.load().then(() => {
      const initial = services.features.webConfig.data.value.qywxAPIConfigs
      setConfigs(initial.length ? initial : [{ corpId: '', secret: '', corpIdOrigin: '' }])
    })
  }, [])

  function addConfig() {
    save([...configs, { corpId: '', secret: '', corpIdOrigin: '' }])
  }
  function removeConfig(index: number) {
    const updated = [...configs]
    updated.splice(index, 1)
    save(updated)
  }
  function updateConfig(key: 'corpId' | 'corpIdOrigin' | 'secret', index: number, value: string) {
    const updated = [...configs]
    updated[index] = { ...updated[index]!, [key]: value }
    save(updated)
  }
  function save(configs: QywxAPIConfig[]) {
    setConfigs(configs)

    const configsToSave = configs
      .map(v => ({ corpId: v.corpId.trim(), corpIdOrigin: v.corpIdOrigin.trim(), secret: v.secret.trim() }))
      .filter(v => v.corpId || v.corpIdOrigin || v.secret)
    void services.features.webConfig.update({
      ...services.features.webConfig.data.value,
      qywxAPIConfigs: configsToSave
    })
  }

  return <div>
    <header css={s.header}>
      <Button type="primary" onClick={addConfig}>添加</Button>
    </header>
    <div css={s.configs}>
      {configs.map((v, index) => <div key={index} css={s.config}>
        <div className="inputs">
          <div>
            <label>corpId</label>
            <Input placeholder="输入 corpId" value={v.corpId} onChange={e => updateConfig('corpId', index, e.target.value)} />
          </div>
          <div>
            <label>corpIdOrigin</label>
            <Input placeholder="输入 corpIdOrigin" value={v.corpIdOrigin} onChange={e => updateConfig('corpIdOrigin', index, e.target.value)} />
          </div>
          <div>
            <label>secret</label>
            <Input placeholder="输入 secret" value={v.secret} onChange={e => updateConfig('secret', index, e.target.value)} />
          </div>
        </div>
        <div className="actions">
          <Popconfirm title="确定要删除吗？此操作无法撤回" onConfirm={() => removeConfig(index)}>
            <Button type="link" danger>删除</Button>
          </Popconfirm>
        </div>
      </div>)}
    </div>
  </div>
}

const s = {
  header: css`
    margin-bottom: 30px;
  `,
  configs: css`
  `,
  config: css`
    display: flex;
    &:not(:last-child) {
      padding-bottom: 30px;
      border-bottom: 1px solid #f0f0f0;
      margin-bottom: 22px;
    }
    .inputs {
      flex: 1;
    }
    .inputs > div {
      display: flex;
      &:not(:last-child) {
        margin-bottom: 12px;
      }
      label {
        width: 8em;
      }
      input {
        width: 30em;
      }
    }
  `
}
